//
//  SegmentView.swift
//  forTest
//
//  Created by CarlsonLee on 2020/4/24.
//  Copyright © 2020 CarlsonLee. All rights reserved.
//

import UIKit

class SegmentView: UIView {

    var bgView: UIScrollView?
    var bottomLine: UIView?
    
    var nColor: UIColor?
    var sColor: UIColor?
    var nSize: CGFloat = 15
    var sSize: CGFloat = 15
    var selectIdx: Int = 0
    var arr: [String] = [String]()
    var items: [SegmentViewItem] = [SegmentViewItem]()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
               
        //底层滚动视图
        bgView = UIScrollView(frame: bounds);
        bgView?.showsHorizontalScrollIndicator = false
        addSubview(bgView!)
        
        //底部线
        bottomLine = UIView()
        bottomLine?.backgroundColor = UIColor.black
        bgView?.addSubview(bottomLine!)
        
        //初始化默认
        nColor = UIColor.lightGray
        sColor = UIColor.gray
    }
    //正常状态
    func normalItem(_ color: UIColor, _ size: CGFloat) {
        nColor = color
        nSize = size
        if items.count > 0 {
            for item in items {
                item.setTitleStyle(nColor!, sColor!, sSize, nSize)
            }
        }
    }
    //选中状态
    func selectItem(_ color: UIColor, _ size: CGFloat) {
        sColor = color
        sSize = size
        if items.count > 0 {
            for item in items {
                item.setTitleStyle(nColor!, sColor!, sSize, nSize)
            }
        }
    }
    //设置标签数组
    func itemsArr(_ arr: [String]) {
        self.arr = arr
        for i in 0..<arr.count {
            let str = arr[i]
            let item = SegmentViewItem(frame: CGRect.zero, title: str)
            item.setTitleStyle(nColor!, sColor!, nSize, sSize)
            item.tag = i
            bgView?.addSubview(item)
            items.append(item)
            
            item.closure = { tag in
                self.setIndex(tag)
            }
        }
        setIndex(selectIdx)
    }
    //设置选中标签
    func setIndex(_ idx: Int) {
        if items.count > 0 && idx < items.count {
            for i in 0..<items.count {
                let state = i==idx
                let item = items[i]
                item.setState(state)
                
                if state {
                    let frame = CGRect(x: item.frame.origin.x, y: item.frame.size.height-4, width: item.frame.size.width, height: 2)
                    UIView.animate(withDuration: 0.25) {
                        self.bottomLine?.frame = frame
                    }
                    
                    checkItem(idx)
                }
            }
        }
    }
    
    //判断标签是否在视图之外
    func checkItem(_ idx: Int) {
        let item = items[idx]
        var point = self.convert(item.frame.origin, to: self)
        var p = bgView?.contentOffset
        if point.x < self.center.x {
            var item1: SegmentViewItem?
            if idx==0 {
                item1 = items[idx]
            }else{
                item1 = items[idx-1]
            }
            point = self.convert((item1?.frame.origin)!, to: self)
            //如果点的视图在外,或者左边的一个item在外
            if point.x-(item1?.frame.size.width)! < 0 {
                p?.x = (item1?.frame.origin.x)!
                bgView?.setContentOffset(p!, animated: true)
            }
        }else{
            var item1: SegmentViewItem?
            if idx==items.count-1 {
                item1 = items[idx]
            }else{
                item1 = items[idx+1]
            }
            point = self.convert((item1?.frame.origin)!, to: self)
            //如果点的视图在外,或者左边的一个item在外
            if point.x+(item1?.frame.size.width)! > bounds.width {
                p?.x = point.x+(item1?.frame.size.width)!-bounds.width
                bgView?.setContentOffset(p!, animated: true)
            }
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        bgView?.frame = bounds
        var f_x: CGFloat = 0.0
        for i in 0..<items.count {
            let item = items[i]
            let str = arr[i]
            var size = str.sizeWithText(font: UIFont(name: "PingFangSC-Regular", size: nSize)!, size: CGSize(width: CGFloat(FLT_MAX), height: 0))
            if size.width < 40 {
                size.width = 60
            }
            size.height = bounds.height
            let frame = CGRect(origin: CGPoint(x: f_x, y: 0), size: size)
            item.frame = frame
            f_x += size.width
        }
        bgView?.contentSize = CGSize(width: f_x, height: bounds.height)
        
        let item = items[selectIdx]
        let frame = CGRect(x: item.frame.origin.x, y: item.frame.size.height-4, width: item.frame.size.width, height: 2)
        bottomLine?.frame = frame;
    }
}

class SegmentViewItem: UIView {
    
    var btn: UIButton?
    var nColor: UIColor?
    var sColor: UIColor?
    var nSize: CGFloat?
    var sSize: CGFloat?
    
    var closure: ((Int)->())?
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    init(frame: CGRect, title: String) {
        super.init(frame: frame)
        
        let bds = CGRect(origin: CGPoint.zero, size: frame.size)
        btn = UIButton(frame: bds)
        btn?.setTitle(title, for: .normal)
        btn?.setTitleColor(nColor, for: .normal)
        addSubview(btn!)
        btn?.addTarget(self, action: #selector(btnResponse), for: .touchUpInside)
    }
    
    func setTitleStyle(_ nColor: UIColor, _ sColor: UIColor, _ nSize: CGFloat, _ sSize: CGFloat) {
        self.nColor = nColor
        self.sColor = sColor
        self.nSize = nSize
        self.sSize = sSize
        
        setState(false)
    }
   func setState(_ state: Bool) {
       let color = state ? sColor:nColor
       let font = state ? UIFont(name: "PingFangSC-Regular", size: sSize!):UIFont(name: "PingFangSC-Regular", size: nSize!)
       btn?.setTitleColor(color, for: .normal)
       btn?.titleLabel?.font = font
   }
    
    @objc func btnResponse() {
        if closure != nil {
            closure?(self.tag)
        }
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        btn?.frame = bounds
    }
}

extension String{

func sizeWithText(font: UIFont, size: CGSize) -> CGSize {
    let attributes = [NSAttributedString.Key.font: font]
    let option = NSStringDrawingOptions.usesLineFragmentOrigin
    let rect:CGRect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil)
        return rect.size;
    }

}
